#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

pthread_cond_t cond;// 条件变量
pthread_mutex_t mutex;// 锁

void* threadrun1(void* arg)
{
  char* name = (char*)arg;
  while (1){
    pthread_mutex_lock(&mutex);
    // 奇数就挂起
    pthread_cond_wait(&cond, &mutex);// 挂起，释放锁，当该函数返回时，进入到临界区，重写持有锁
    printf("%s is waked up...\n", name);
    sleep(1);
    pthread_mutex_unlock(&mutex);
  }
}

void* threadrun2(void* arg)
{
  char* name = (char*)arg;
  while (1){
    //pthread_mutex_lock(&mutex);
    // 唤醒一个等待队列中的线程
    sleep(1);
    //pthread_cond_signal(&cond);
    pthread_cond_broadcast(&cond);
    //printf("%s is wakeing up a thread...\n", name);
    printf("%s is wakeing up all threads...\n", name);
    //pthread_mutex_unlock(&mutex);
    sleep(1);
  }
}

int main()
{
  pthread_t pthread1, pthread2, pthread3, pthread4, pthread5;
  // 初始化条件变量
  pthread_cond_init(&cond, NULL);
  pthread_mutex_init(&mutex, NULL);
  
  pthread_create(&pthread1, NULL, threadrun1, (void*)"pthread 1");
  pthread_create(&pthread2, NULL, threadrun1, (void*)"pthread 2");
  pthread_create(&pthread3, NULL, threadrun1, (void*)"pthread 3");
  pthread_create(&pthread4, NULL, threadrun1, (void*)"pthread 4");
  pthread_create(&pthread5, NULL, threadrun2, (void*)"pthread 5");
  
  pthread_join(pthread1, NULL);
  pthread_join(pthread2, NULL);
  pthread_join(pthread3, NULL);
  pthread_join(pthread4, NULL);
  pthread_join(pthread5, NULL);
  
  pthread_mutex_destroy(&mutex);
  pthread_cond_destroy(&cond);
  return 0;
}
